package com.ldk.api.handler;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import com.ldk.base.framework.util.*;
import com.ldk.framework.entity.*;
import com.ldk.framework.service.*;

import org.apache.commons.lang.StringUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.config.AlipayConfig;
import com.ldk.api.ApiVersion;
import com.ldk.api.CheckToken;
import com.ldk.api.Consts;
import com.ldk.api.ErrorCode;
import com.ldk.api.FileItem;
import com.ldk.api.RequestPlatform;
import com.ldk.api.ResponseObject;
import com.ldk.api.ResponseResult;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.framework.enums.TripNoType;
import com.ldk.framework.enums.PayType;
import com.ldk.framework.enums.PlatformUserType;
import com.ldk.framework.enums.TradePayStatus;
import com.ldk.framework.enums.UserStatus;
import com.weixin.api.WxMpService;
import com.weixin.api.WxMpServiceImpl;
import com.weixin.bean.result.WxMpPrepayIdResult;
import com.weixin.common.util.crypto.WxCryptUtil;
import com.weixin.util.WxConfig;

/**
 * 用户模块接口
 *
 * @author xiangwl
 */
public class UserRequestHandler extends BaseRequestHandler {
    @Autowired
    private IUserService userService;
    @Autowired
    private IPhoneValidcodeService phoneValidcodeService;
    @Autowired
    private IRechargeOrderService rechargeOrderService;
    @Autowired
    private ITenpayService tenpayService;
    @Autowired
    private IPushMessageService pushMessageService;
    @Autowired
    private IDriverService driverService;
    @Autowired
    private ITicketUserService ticketUserService;


    /**
     * 用户注册
     *
     * @param parms {phoneNo, validCode, clientInfo}
     * @return
     * @paramphoneNo 手机号
     */
    @ApiVersion(value = {1})
    public ResponseObject register(Map<String, Object> parms) {

        ResponseObject response = ResponseResult.create("user", "register");

        if (!checkRequireParms(parms, "phoneNo", "validCode", "passWord")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String validCode = String.valueOf(parms.get("validCode"));
        String phoneNo = String.valueOf(parms.get("phoneNo"));
        String passWord = String.valueOf(parms.get("passWord"));

        String clientInfo = String.valueOf(parms.get("clientInfo"));
        double lon = ConvertUtil.parseDouble(parms.get("lon"));
        double lat = ConvertUtil.parseDouble(parms.get("lat"));

        String content = String.format("%s%s", validCode, clientInfo);
        String token = TokenUtil.encrypt(phoneNo, content);

        String commonId = ConvertUtil.parseString(parms.get("commonId"));
        long rCommonId = 0L;


        //ycs 190712
        /*
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        if (StringUtils.isBlank(passWord)) {
            return ResponseResult.exception(response, ErrorCode.PASSWORD_EMPTY);
        }
        if (StringUtils.isBlank(validCode)) {
            return ResponseResult.exception(response,
                    ErrorCode.VALIDE_CODE_EMPTY);
        }
        if (!phoneValidcodeService.checkInputCorrect("", phoneNo, validCode)) {
            return ResponseResult.exception(response,
                    ErrorCode.VALID_CODE_ERROR);
        }
        // 判断验证码是否过期
        if (phoneValidcodeService.checkExpired("", phoneNo, validCode)) {
            return ResponseResult.exception(response,
                    ErrorCode.VALIDE_CODE_TIME_OUT);
        }
        */
        /*if(!StringUtils.isBlank(commonId)) {
            if(!RegexUtil.isUInt(commonId)) {
                return ResponseResult.exception(response, ErrorCode.COMMONID_FORMAT_ERROR);
            }
            if((commonId.length() !=6 && commonId.length() !=8)) {
                return ResponseResult.exception(response, ErrorCode.COMMONID_FORMAT_ERROR);
            }

            if(commonId.length() ==6) {
                if (!driverService.existDCommonId(ConvertUtil.parseLong(commonId))) {
                    return ResponseResult.exception(response, ErrorCode.COMMONID_NON_EXIST);
                } else {
                    rCommonId = ConvertUtil.parseLong(commonId);
                }
            }
            if(commonId.length() ==8) {
                if (!userService.existUCommonId(ConvertUtil.parseLong(commonId))) {
                    return ResponseResult.exception(response, ErrorCode.COMMONID_NON_EXIST);
                } else {
                    rCommonId = ConvertUtil.parseLong(commonId);
                }
            }
        }*/

        //如果推荐码不为空
        TicketUser ticketUser = null;
        if (!TextUtils.isEmpty(commonId)) {
            //查询票务经理
            ticketUser = ticketUserService.getTicketInfoBySaleNo("", commonId);
            if (ticketUser == null) {
                return ResponseResult.exception(response, ErrorCode.TICKET_SALENO_EXIST);
            }
        }

        User query = new User();
        query.setPhoneNo(phoneNo);

        User user = userService.selectOne("", query);
        if (user != null) {
            return ResponseResult.exception(response, ErrorCode.USER_EXIST);
        }
       /* Boolean exist = user == null ? false : true;
        // 如果存在且被禁用
        if (exist && !user.getEnabled()) {
            return ResponseResult.exception(response, ErrorCode.USER_DISABLE);
        }*/
        // 修改用户信息
        User updateUser = new User();
        long registerTime = SystemUtil.getAllSeconds();
        updateUser.setPhoneNo(phoneNo);
        updateUser.setUserRank(1);// 1普通
        updateUser.setRegisterTime(registerTime);
        updateUser.setBalance(0.0);
        updateUser.setEnabled(true);
        updateUser.setRemark("");
        updateUser.setPicture("");
        String openId = OpenIdUtil.encrypt(phoneNo, registerTime, Consts.System_Sign_EncryptKey);
        updateUser.setOpenId(openId);
        updateUser.setClientInfo(clientInfo);
        updateUser.setLoginTime(SystemUtil.getAllSeconds());
        updateUser.setStatus(UserStatus.OnLine.getValue());
        updateUser.setToken(token);
        updateUser.setLon(lon);
        updateUser.setLat(lat);
        //支付密码 手机号后6位
        String payPwd = phoneNo.substring(5, 11);
        String ecPayPwd = encodePayPwd(payPwd);
        updateUser.setPayPwd(ecPayPwd);

        String slat = SystemUtil.generateSalt(6);
        String encryptPwd = EncryptUtil.md5(passWord + slat);
        updateUser.setPassword(encryptPwd);
        updateUser.setSalt(slat);
        updateUser.setUploadFlag(0);

        /*updateUser.setCoupon(0.0);
        long uCommonId = userService.generateUCommonId();
        updateUser.setuCommonId(uCommonId);
        updateUser.setrCommonId(rCommonId);*/

        int row = 0;
        try {
            row = userService.insert("", updateUser);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        if (row > 0) {
            if (ticketUser != null) {
                ticketUserService.saveTicketBySaleNo("", phoneNo, ticketUser);
            }
            // 验证码使用后马上过期
            phoneValidcodeService.validCodeExpired("", phoneNo);
            // 重新查询一次
            User result = userService.selectOne("", query);

            // 奖励现金卷或优惠卷
            if (rCommonId > 0) {
                //userService.insertCoupon(result);
            }

            ResponseResult.success(response, result);
        } else {
            ResponseResult.exception(response, ErrorCode.LOGIN_FAILED);
        }
        return response;
    }

    /**
     * 用户登陆
     *
     * @param parms {phoneNo, validCode, clientInfo}
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject loginPwd(Map<String, Object> parms) {

        ResponseObject response = ResponseResult.create("user", "loginPwd");

        if (!checkRequireParms(parms, "phoneNo", "passWord")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String passWord = String.valueOf(parms.get("passWord"));
        String phoneNo = String.valueOf(parms.get("phoneNo"));
        String clientInfo = String.valueOf(parms.get("clientInfo"));
        double lon = ConvertUtil.parseDouble(parms.get("lon"));
        double lat = ConvertUtil.parseDouble(parms.get("lat"));

        String content = String.format("%s%s", passWord, clientInfo);
        String token = TokenUtil.encrypt(phoneNo, content);
        //苹果审核测试帐呈
        if ("18385099600".equals(phoneNo) && "123456".equalsIgnoreCase(passWord)) {
            User user = userService.getUserByPhone("", phoneNo);
            user.setToken(token);

            User entity = new User();
            entity.setUserId(user.getUserId());
            entity.setToken(token);

            try {
                userService.updateByKey("", entity);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }

            return ResponseResult.success(response, user);
        }
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        if (StringUtils.isBlank(passWord)) {
            return ResponseResult.exception(response, ErrorCode.PASSWORD_EMPTY);
        }
        User query = new User();
        query.setPhoneNo(phoneNo);

        User user = userService.selectOne("", query);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        if (!user.getEnabled()) {
            return ResponseResult.exception(response, ErrorCode.USER_DISABLE);
        }
        String encryptPwd = EncryptUtil.md5(passWord + user.getSalt());
        if (!encryptPwd.equalsIgnoreCase(user.getPassword())) {
            return ResponseResult.exception(response, ErrorCode.USER_LOG_PWD_ERROR);
        }
        // 修改用户信息
        User updateUser = new User();
        updateUser.setUserId(user.getUserId());
        updateUser.setClientInfo(clientInfo);
        updateUser.setLoginTime(SystemUtil.getAllSeconds());
        updateUser.setStatus(UserStatus.OnLine.getValue());
        updateUser.setToken(token);
        updateUser.setLon(lon);
        updateUser.setLat(lat);
        int row = 0;
        try {
            row = userService.updateByKey("", updateUser);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (row > 0) {
            // 重新查询一次
            User result = userService.selectOne("", query);
            ResponseResult.success(response, result);
        } else {
            ResponseResult.exception(response, ErrorCode.LOGIN_FAILED);
        }
        return response;
    }

    /**
     * 用户登陆
     *
     * @param parms {phoneNo, validCode, clientInfo}
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject login(Map<String, Object> parms) {

        ResponseObject response = ResponseResult.create("user", "login");

        if (!checkRequireParms(parms, "phoneNo", "validCode")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String validCode = String.valueOf(parms.get("validCode"));
        String phoneNo = String.valueOf(parms.get("phoneNo"));
        String clientInfo = String.valueOf(parms.get("clientInfo"));
        double lon = ConvertUtil.parseDouble(parms.get("lon"));
        double lat = ConvertUtil.parseDouble(parms.get("lat"));

        String content = String.format("%s%s", validCode, clientInfo);
        String token = TokenUtil.encrypt(phoneNo, content);
        //苹果审核测试帐呈
        if ("18385099600".equals(phoneNo) && "123456".equalsIgnoreCase(validCode)) {
            User user = userService.getUserByPhone("", phoneNo);
            user.setToken(token);

            User entity = new User();
            entity.setUserId(user.getUserId());
            entity.setToken(token);

            try {
                userService.updateByKey("", entity);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }

            return ResponseResult.success(response, user);
        }
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        if (StringUtils.isBlank(validCode)) {
            return ResponseResult.exception(response,
                    ErrorCode.VALIDE_CODE_EMPTY);
        }
        if (!phoneValidcodeService.checkInputCorrect("", phoneNo, validCode)) {
            return ResponseResult.exception(response,
                    ErrorCode.VALID_CODE_ERROR);
        }
        // 判断验证码是否过期
        if (phoneValidcodeService.checkExpired("", phoneNo, validCode)) {
            return ResponseResult.exception(response,
                    ErrorCode.VALIDE_CODE_TIME_OUT);
        }

        User query = new User();
        query.setPhoneNo(phoneNo);

        User user = userService.selectOne("", query);
        Boolean exist = user == null ? false : true;
        // 如果存在且被禁用
        if (exist && !user.getEnabled()) {
            return ResponseResult.exception(response, ErrorCode.USER_DISABLE);
        }
        // 修改用户信息
        User updateUser = new User();
        if (!exist) {// 如果用户不存在则新建一个用户
            long registerTime = SystemUtil.getAllSeconds();
            updateUser.setPhoneNo(phoneNo);
            updateUser.setUserRank(1);// 1普通
            updateUser.setRegisterTime(registerTime);
            updateUser.setBalance(0.0);
            updateUser.setEnabled(true);
            updateUser.setRemark("");
            updateUser.setPicture("");
            //支付密码 手机号后6位
            String payPwd = phoneNo.substring(5, 11);
            String ecPayPwd = encodePayPwd(payPwd);
            updateUser.setPayPwd(ecPayPwd);
            String openId = OpenIdUtil.encrypt(phoneNo, registerTime, Consts.System_Sign_EncryptKey);
            updateUser.setOpenId(openId);
        } else {
            updateUser.setUserId(user.getUserId());
        }
        updateUser.setClientInfo(clientInfo);
        updateUser.setLoginTime(SystemUtil.getAllSeconds());
        updateUser.setStatus(UserStatus.OnLine.getValue());
        updateUser.setToken(token);
        updateUser.setLon(lon);
        updateUser.setLat(lat);

        int row = 0;
        try {
            if (exist) {
                row = userService.updateByKey("", updateUser);
            } else {
                row = userService.insert("", updateUser);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        if (row > 0) {
            // 验证码使用后马上过期
            phoneValidcodeService.validCodeExpired("", phoneNo);
            // 重新查询一次
            User result = userService.selectOne("", query);
            ResponseResult.success(response, result);
        } else {
            ResponseResult.exception(response, ErrorCode.LOGIN_FAILED);
        }
        return response;
    }

    /**
     * 修改签名
     *
     * @param parms {phoneNo, remark}
     * @return
     * @paramopenId 用户openId
     * @paramremark 签名
     */
    @ApiVersion(value = {1})
    public ResponseObject updateRemark(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("user", "updateRemark");
        if (!checkRequireParms(parms, "openId", "remark")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String remark = ConvertUtil.parseString(parms.get("remark"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        User query = new User();
        query.setOpenId(openId);

        User user = userService.selectOne("", query);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        Boolean succeed = userService.updateRemark("", user.getUserId(), remark);
        if (succeed) {
            user.setRemark(remark);
            ResponseResult.success(response, user);
        } else {
            ResponseResult.exception(response, ErrorCode.USER_UPDATE_REMARK_FAILED);
        }
        return response;
    }

    /**
     * 修改头像
     *
     * @param parms {phoneNo, fileList}
     * @return
     * @paramopenId 用户openId
     * @paramfileList 图片列表
     */
    @ApiVersion(value = {1})
    public ResponseObject updatePicture(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("user", "updatePicture");
        if (!checkRequireParms(parms, "openId", "fileList")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        List<FileItem> fileList = null;
        if (parms.get("fileList") != null) {
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> list = (List<FileItem>) parms.get("fileList");
                fileList = list;
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        if (fileList == null || fileList.isEmpty() || StringUtils.isBlank(fileList.get(0).getFileFullUrl())) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }

        String picture = fileList.get(0).getFileFullUrl();
        User query = new User();
        query.setOpenId(openId);

        User user = userService.selectOne("", query);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        Boolean succeed = userService.updatePicture("", user.getUserId(), picture);
        if (succeed) {
            user.setPicture(picture);
            ResponseResult.success(response, user);
        } else {
            ResponseResult.exception(response, ErrorCode.USER_UPDATE_PICTURE_FAILED);
        }

        return response;
    }

    /**
     * 修改昵称
     *
     * @param parms {phoneNo, nickName}
     * @return
     * @paramopenId 用户openId
     * @paramnickName 昵称
     */
    @ApiVersion(value = {1})
    public ResponseObject updateNickName(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("user", "updateNickName");
        if (!checkRequireParms(parms, "openId", "nickName")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }

        String openId = ConvertUtil.parseString(parms.get("openId"));
        String nickName = ConvertUtil.parseString(parms.get("nickName"));
        User query = new User();
        query.setOpenId(openId);

        User user = userService.selectOne("", query);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        Boolean succeed = userService.updateNickName("", user.getUserId(), nickName);
        if (succeed) {
            user.setNickName(nickName);
            ResponseResult.success(response, user);
        } else {
            ResponseResult.exception(response, ErrorCode.USER_UPDATE_NICKNAME_FAILED);
        }
        return response;
    }

    /**
     * 修改位置信息
     *
     * @param parms {phoneNo, lon, lat}
     * @return
     * @paramopenId 用户openId
     * @paramlon 用户当前位置经度
     * @paramlat 用户当前位置纬度
     */
    @ApiVersion(value = {1})
    public ResponseObject updateLocation(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("user", "updateLocation");
        if (!checkRequireParms(parms, "openId", "lon", "lat")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }

        String openId = ConvertUtil.parseString(parms.get("openId"));
        double lon = ConvertUtil.parseDouble(parms.get("lon"));
        double lat = ConvertUtil.parseDouble(parms.get("lat"));
        User query = new User();
        query.setOpenId(openId);

        User user = userService.selectOne("", query);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        Boolean succeed = userService.updateLocation("", user.getUserId(), lon, lat);
        if (succeed) {
            user.setLon(lon);
            user.setLat(lat);
            ResponseResult.success(response, user);
        } else {
            ResponseResult.exception(response, ErrorCode.USER_UPDATE_LOCATION_FAILED);
        }

        return response;
    }


    /**
     * 获取用户信息
     *
     * @param parms{phoneNo}
     * @return
     * @paramphoneNo 用户手机号
     */
    @ApiVersion(value = {1})
    public ResponseObject getUserInfo(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("user", "getUserInfo");
        if (!checkRequireParms(parms, "phoneNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        if (StringUtils.isEmpty(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        User user = userService.getUserByPhone("", phoneNo);
        if (user == null) {
            ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        } else {
            ResponseResult.success(response, user);
        }
        return response;
    }

    /**
     * 用户充值
     *
     * @param parms {openId, rechargeMoney, giveMoney, payId, ip}
     * @return
     * @paramopenId 用户openId
     * @paramrechargeMoney 充值金额
     * @paramgiveMoney 充值赠送金额，默认为0
     * @parampayId 支付方式ID 1支付宝 2微信支付
     * @paramip 微信支付时 客户端终端IP,其他支付时为空
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.client)
    public ResponseObject recharge(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("user", "recharge");
        if (!checkRequireParms(parms, "openId", "rechargeMoney", "giveMoney", "payId", "ip")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = String.valueOf(parms.get("openId"));
        Double rechargeMoney = ConvertUtil.parseDouble(parms.get("rechargeMoney"));
        Double giveMoney = ConvertUtil.parseDouble(parms.get("giveMoney"), 0);
        int payId = ConvertUtil.parseInt(parms.get("payId"));
        String ip = String.valueOf(parms.get("ip"));
        ip = "127.0.0.1";
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        //判断用户是否存在
        User user = userService.getUserByOpenId("", openId);
        if (user == null) {
            ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }

        if (!(rechargeMoney > 0)) {
            return ResponseResult.exception(response, ErrorCode.USER_RECHARGE_MOENY_LESS_ZERO);
        }
        //支付方式判断
        //必须是支付宝或微信支付
        if (payId != PayType.Alipay.getId() &&
                payId != PayType.Tenpay.getId()) {
            return ResponseResult.exception(response, ErrorCode.PAYMENT_NOT_EXIST);
        }
        //如果是微信支付，需要判断openId,ip不能为空
        if (payId == PayType.Tenpay.getId()) {
            if (StringUtils.isBlank(ip)) {
                return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
            }
        }
        String payName = PayType.getPayName(payId);
        //创建充值订单实体
        String orderNo = SystemUtil.generateOrderNo(TripNoType.CZ.getPrefix());
        RechargeOrder entity = new RechargeOrder();
        entity.setRechargeOrderNo(orderNo);
        entity.setRechargeUser(openId);
        entity.setRechargeMoney(rechargeMoney);
        entity.setGiveMoney(giveMoney);
        entity.setUserType(PlatformUserType.CLIENT_USER.getValue());
        entity.setCreateTime(SystemUtil.getAllSeconds());
        entity.setPayId(payId);
        entity.setPayName(payName);
        entity.setPayStatus(TradePayStatus.WAIT_BUYER_PAY.getValue());

        Boolean succeed = false;
        try {
            int row = rechargeOrderService.insert("", entity);
            succeed = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        //创建充值订单成功
        if (!succeed) {
            return ResponseResult.exception(response, ErrorCode.USER_CREATE_RECHARGE_ORDER_FAILED);
        }
        RechargeOrder orderQuery = new RechargeOrder();
        orderQuery.setRechargeOrderNo(orderNo);

        RechargeOrder order = rechargeOrderService.selectByKey("", orderQuery);

        Map<String, Object> result = BeanUtil.toMapByFastjson(order);
        String outTradeNo = orderNo;
        if (payId == PayType.Alipay.getId()) {
            result.put("callbackUrl", Consts.PAYNOTIFY_TENPAY_CALLBACK_URL);
            result.put("outTradeNo", outTradeNo);
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.private_key, "json", AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type);
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody(Consts.SystemName + "用户充值订单");
            model.setSubject(Consts.SystemName);
            model.setOutTradeNo(outTradeNo);
            model.setSellerId(AlipayConfig.partner_id);
            model.setTimeoutExpress("90m");
            model.setTotalAmount(rechargeMoney + "");
            model.setProductCode("QUICK_MSECURITY_PAY");
            request.setBizModel(model);
            request.setNotifyUrl(Consts.PAYNOTIFY_ALIPAY_CALLBACK_URL);

            String aliPrePayResult = "";
            try {
                AlipayTradeAppPayResponse response1 = alipayClient.sdkExecute(request);
                aliPrePayResult = response1.getBody();
                logger.error("aliPrePayResult=" + aliPrePayResult);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
            result.put("aliPrePayResult", aliPrePayResult);
        } else {
            float amt = rechargeMoney.floatValue();
            String body = Consts.SystemName + "用户充值订单";
            String tradeType = "APP";
            WxMpService wxMpService = new WxMpServiceImpl();
            WxMpPrepayIdResult prepayIdResult = wxMpService.getPrepayId("", outTradeNo, amt, body, tradeType, ip, Consts.PAYNOTIFY_TENPAY_CALLBACK_URL);
            logger.error("recharge.prepayIdResult=" + JSON.toJSONString(prepayIdResult));
            //如果获取成功
            if (prepayIdResult.isResultSuccess()) {
                //设置回调地址
                result.put("callbackUrl", Consts.PAYNOTIFY_TENPAY_CALLBACK_URL);
                result.put("outTradeNo", outTradeNo);

                String nonce_str = SystemUtil.getAllSeconds() + "";
                String timestamp = SystemUtil.getAllSeconds() + "";

                SortedMap<String, String> packageParams = new TreeMap<String, String>();
                packageParams.put("appid", WxConfig.AppId);
                packageParams.put("noncestr", nonce_str);
                packageParams.put("package", "Sign=WXPay");
                packageParams.put("partnerid", prepayIdResult.getMch_id());
                packageParams.put("prepayid", prepayIdResult.getPrepay_id());
                packageParams.put("timestamp", timestamp);

                String sign = WxCryptUtil.createSign(packageParams, WxConfig.SignKey);

                Map<String, Object> wxResultMap = new HashMap<String, Object>();
                wxResultMap.put("appid", WxConfig.AppId);
                wxResultMap.put("partnerid", prepayIdResult.getMch_id());
                wxResultMap.put("prepayid", prepayIdResult.getPrepay_id());
                wxResultMap.put("noncestr", nonce_str);
                wxResultMap.put("timestamp", timestamp);
                wxResultMap.put("packages", "Sign=WXPay");//android package是关键字，不能解析，换作packages
                wxResultMap.put("sign", sign);

                result.put("wxPrePayResult", wxResultMap);
                try {
                    //同时新增微信支付记录
                    Tenpay tenpay = new Tenpay();
                    tenpay.setAppid(prepayIdResult.getAppid());
                    tenpay.setBody(body);
                    tenpay.setMchId(prepayIdResult.getMch_id());
                    tenpay.setOutTradeNo(outTradeNo);
                    ;
                    tenpay.setTradeType(tradeType);
                    tenpay.setTotalFee(rechargeMoney);
                    tenpay.setTimeStart(SystemUtil.getDateString(new Date(), "yyyyMMddHHmmss"));
                    tenpay.setSpbillCreateIp(ip);
                    tenpay.setPrepayId(prepayIdResult.getPrepay_id());
                    tenpay.setCodeUrl(prepayIdResult.getCode_url());
                    tenpay.setOpenid("");

                    tenpayService.insert("", tenpay);
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }

            }
        }
        ResponseResult.success(response, result);

        return response;
    }

    /**
     * 获取用户充值记录列表
     *
     * @param parms {openId, pageIndex, pageSize}
     * @return
     * @paramopenId 用户openId
     * @parampageIndex 分页索引
     * @parampageSize 分页每页显示条数
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.client)
    public ResponseObject getRechargeRecordList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("user", "getRechargeRecordList");
        if (!checkRequireParms(parms, "openId", "pageIndex", "pageSize")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = String.valueOf(parms.get("openId"));
        int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);

        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        User user = userService.getUserByOpenId("", openId);
        if (user == null) {
            ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        int offset = (pageIndex - 1) * pageSize;
        Sort sort = new Sort(Direction.DESC, "pay_time");
        CustomPageable pageable = new CustomPageable(offset, pageSize, sort);

        RechargeOrder query = new RechargeOrder();
        query.setRechargeUser(openId);
        query.setPayStatus(TradePayStatus.TRADE_SUCCESS.getValue());

        List<RechargeOrder> result = rechargeOrderService.selectList("", query, pageable);
        if (result == null) {
            ResponseResult.exception(response, ErrorCode.USER_RECHARGE_ORDER_NO_MORE);
        } else {
            ResponseResult.success(response, result);
        }

        return response;
    }


    /**
     * 获取用户推送消息列表
     *
     * @param parms
     * @return
     * @paramopenId 用户openId
     * @parammodule 消息模块
     * @parampageIndex 分页索引
     * @parampageSize 分页每页显示条数
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.client)
    public ResponseObject getPushMessageList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("user", "getPushMessageList");
        if (!checkRequireParms(parms, "openId", "module", "pageIndex", "pageSize")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        String module = ConvertUtil.parseString(parms.get("module"));
        int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);
        int offset = (pageIndex - 1) * pageSize;

        Sort sort = new Sort(Direction.DESC, "push_time");
        sort.and(new Sort(Direction.ASC, "module"));
        CustomPageable pageable = new CustomPageable(offset, pageSize, sort);

        PushMessage query = new PushMessage();
        query.setToUser(openId);
        query.setModule(module);
        List<PushMessage> result = pushMessageService.selectList("", query, pageable);

        ResponseResult.success(response, result);

        return response;
    }

    /**
     * 设置支付密码
     *
     * @param parms
     * @return
     * @paramopenId 用户openId
     * @parampayPwd 支付密码
     * @paramvalidCode 验证码
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.client)
    public ResponseObject setPayPwd(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("user", "setPayPwd");
        if (!checkRequireParms(parms, "openId", "payPwd", "validCode")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String payPwd = ConvertUtil.parseString(parms.get("payPwd"));
        String validCode = ConvertUtil.parseString(parms.get("validCode"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(payPwd)) {
            return ResponseResult.exception(response, ErrorCode.PASSWORD_EMPTY);
        }
        if (StringUtils.isBlank(validCode)) {
            return ResponseResult.exception(response, ErrorCode.VALIDE_CODE_EMPTY);
        }
        User user = userService.getUserByOpenId("", openId);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        String phoneNo = user.getPhoneNo();
        if (phoneValidcodeService.checkExpired("", phoneNo, validCode)) {
            return ResponseResult.exception(response, ErrorCode.VALIDE_CODE_TIME_OUT);
        }
        Boolean success = false;
        try {
            String ecPayPwd = encodePayPwd(payPwd);
            User entity = new User();
            entity.setUserId(user.getUserId());
            entity.setPayPwd(ecPayPwd);
            int row = userService.updateByKey("", entity);
            success = row > 0;
            //设置成功验证码过期
            phoneValidcodeService.validCodeExpired("", phoneNo);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            ResponseResult.success(response, "设置成功");
        } else {
            ResponseResult.exception(response, ErrorCode.USER_SET_PAY_PWD_FAILED);
        }

        return response;
    }

    /**
     * 找回登录密码
     *
     * @param parms
     * @return
     * @paramopenId 用户openId
     * @parampayPwd 支付密码
     * @paramvalidCode 验证码
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.client)
    public ResponseObject findPwd(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("user", "findPwd");
        if (!checkRequireParms(parms, "phoneNo", "pwd", "validCode")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        String pwd = ConvertUtil.parseString(parms.get("pwd"));
        String validCode = ConvertUtil.parseString(parms.get("validCode"));
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        if (StringUtils.isBlank(pwd)) {
            return ResponseResult.exception(response, ErrorCode.PASSWORD_EMPTY);
        }
        if (StringUtils.isBlank(validCode)) {
            return ResponseResult.exception(response, ErrorCode.VALIDE_CODE_EMPTY);
        }
        User user = userService.getUserByPhone("", phoneNo);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        if (phoneValidcodeService.checkExpired("", phoneNo, validCode)) {
            return ResponseResult.exception(response, ErrorCode.VALIDE_CODE_TIME_OUT);
        }
        Boolean success = false;
        try {
            String slat = SystemUtil.generateSalt(6);
            String encryptPwd = EncryptUtil.md5(pwd + slat);

            User entity = new User();
            entity.setUserId(user.getUserId());
            entity.setPassword(encryptPwd);
            entity.setSalt(slat);
            int row = userService.updateByKey("", entity);
            success = row > 0;
            //设置成功验证码过期
            phoneValidcodeService.validCodeExpired("", phoneNo);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            ResponseResult.success(response, "找回成功");
        } else {
            ResponseResult.exception(response, ErrorCode.USER_SET_PAY_PWD_FAILED);
        }
        return response;
    }

    /**
     * 修改登录密码
     *
     * @param parms
     * @return
     * @paramopenId 用户openId
     * @parampayPwd 支付密码
     * @paramvalidCode 验证码
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.client)
    public ResponseObject updatePwd(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("user", "updatePwd");
        if (!checkRequireParms(parms, "openId", "oldPassword", "newPassword")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String oldPassword = ConvertUtil.parseString(parms.get("oldPassword"));
        String newPassword = ConvertUtil.parseString(parms.get("newPassword"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(oldPassword)) {
            return ResponseResult.exception(response, ErrorCode.PASSWORD_EMPTY);
        }
        if (StringUtils.isBlank(newPassword)) {
            return ResponseResult.exception(response, ErrorCode.PASSWORD_EMPTY);
        }

        User user = userService.getUserByOpenId("", openId);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }

        String salt = user.getSalt();
        String textPwd = String.format("%s%s", oldPassword, salt);
        String md5Pwd = EncryptUtil.md5(textPwd);
        if (user.getEnabled() == null || !user.getEnabled()) {
            return ResponseResult.exception(response, ErrorCode.USER_DISABLE);
        }
        if (!md5Pwd.equalsIgnoreCase(user.getPassword())) {
            return ResponseResult.exception(response, ErrorCode.PASSWORD_ERROR);
        }

        int row = 0;
        try {
            //生成新的密码
            String newtextPwd = String.format("%s%s", newPassword, salt);
            String newmd5Pwd = EncryptUtil.md5(newtextPwd);
            User updateUser = new User();
            updateUser.setUserId(user.getUserId());
            updateUser.setSalt(salt);
            updateUser.setPassword(newmd5Pwd);
            row = userService.updateByKey("", updateUser);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (row > 0) {
            ResponseResult.success(response, "修改成功");
        } else {
            ResponseResult.exception(response, ErrorCode.USER_SET_PAY_PWD_FAILED);
        }
        return response;
    }

}
